package ru.arriah.servicedesk.web.chief.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class DisplayRequestsListAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;

   public DisplayRequestsListAction() throws NamingException {
      super();

      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
   } 
    
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
        int page = idVal(request.getParameter("page"));        
        int itemsPerPage = Integer.parseInt(config.getProperty("ITEMS_PER_PAGE"));
        IntWrapper records = new IntWrapper(0);
        
        RequestManagerLocalObject requestManager = 
          requestManagerHome.create();
        
        String order = request.getParameter("order");
        String orderBy = request.getParameter("orderBy");
        
        order = (order == null) ? "" : order;                
        orderBy = (orderBy == null) ? "" : orderBy;                      
        
        Collection<RequestBean> requestsList = 
          requestManager.selectRequests(
            orderBy, 
            order,
            page,
            itemsPerPage,
            records,
            "'2','3','4','5','6'"
          );                     
        
        requestManager.remove();                      
 
        this.pageNavigationToRequest(
          page,          
          records.getValue(), 
          "chiefui?_action=listRequests&orderBy="+orderBy+"&order="+order+"&page=",
          request
        );
                
        request.setAttribute("requestsList", requestsList);               
        request.setAttribute("order", (order.equals("ASC") ? "DESC" : "ASC"));        
        return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new InternalException("ErrorMessage.internal");
      }
   }
}